import logging
import formbuild
from pylons.decorators import rest
from eshop.lib.base import *


log = logging.getLogger(__name__)

class UserController(BaseController):

    def list(self):
        c.users = model.User.q.all()
        return render('/admin/user_list.mako')
    
    def add(self):
        c.groups = model.Group.q.all()
        c.roles = model.Role.q.all()
        return render('/admin/user_add.mako')
    
    def delete(self, id):
        model.User.q.get(id).delete()
        redirect_to(action='index', id=None)
    
    def edit (self, id):
        c.user = model.User.q.get(id)
        c.groups = model.Group.q.all()
        return render('/admin/user_edit.mako')

    def index(self):
        redirect_to(action='list')
    
    def view (self, id=None):
        c.user = model.User.q.get(id)        
        return render('/admin/user_view.mako')
    
    def save_edit(self, id):
        user = model.User.q.get(id)
        self.__populate_user(user, request)
        redirect_to(action='index')
        
    def save_add(self):
        user = model.User(id=None)
        self.__populate_user(user, request)
        model.flush_all()
        redirect_to(action='index')
        
    @rest.dispatch_on(POST='register_user')
    def register(self):
        c.form = model.forms.build.StandardForm(dict(request.params))
        return render('/admin/registretion_form.mako')

    def register_user(self):
        c.captcha = session.get('ESHOP_CAPTHCHA')     
        results, errors, response = formbuild.handle(  
            schema=model.forms.schema.RegisterFormSchema(),  
            template='/admin/registretion_form.mako',  
            form=model.forms.build.StandardForm  
        )  
        print errors
        if response:  
             return response         
        username = request.params.get('username')
        user = model.User.q.filter_by(username=username).first() 
        print username        
        print user        
        if user :
            errors['username']="Anfortunately login \"%s\" is buzy" % username
            print errors
            return render('/admin/registretion_form.mako')
        user = model.User(id=None)
        user.username = request.params.get('username')
        user.password = request.params.get('password')
        user.email = request.params.get('email')
        model.flush_all()
        redirect_to(action='list')
 
    def __populate_user(self, user, request):
        user.username = request.params.get('username')
        user.password = request.params.get('password')
        user.email = request.params.get('email')
        user.group = model.Group.q.get(request.params.get('group_id'))
        user.roles = []
        for k, v in request.params.iteritems():
            if k.startswith('$role.'):
                role = model.Role.q.get(k.replace('$role.',''))
                user.roles.append(role)

